//
//  MainManager.m
//  KingSelected
//
//  Created by 杨鹏 on 2023/10/27.
//

#import "MainManager.h"
#import "AppDelegate.h"
#import "TabbarController.h"
#import "BaseNaviViewController.h"
#import "LoginViewController.h"

static MainManager *_manager = nil;
static dispatch_once_t onceToken;

@implementation MainManager

+ (MainManager *)sharedManager {
    dispatch_once(&onceToken, ^{
        _manager = [[self alloc] init];
    });
    return _manager;
}

- (instancetype)init {
    if (self = [super init]) {
        self.token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
        UserModel *model = [SaveManager getUserModel];
        if (model) {
            self.user = model;
        }
    }
    return self;
}

- (BOOL)isLogin {
    return self.token.length;
}

- (void)logout {
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"token"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"phone"];
    [SaveManager clearUserModel];
    _token = nil;
    _user = nil;
    [self setRootController];
}

- (void)setRootController {
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UIWindow *window = delegate.window;
    if (!window) {
        window = delegate.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        window.backgroundColor = [UIColor whiteColor];
        [window makeKeyAndVisible];
    }
    if ([self isLogin]) {
        window.rootViewController = [[TabbarController alloc] init];
    }else {
        window.rootViewController = [[BaseNaviViewController alloc] initWithRootViewController:[[LoginViewController alloc] init]];
    }
}

- (void)setUser:(UserModel *)user {
    _user = user;
    if (user.token.length > 0) {
        self.token = user.token;
        [[NSUserDefaults standardUserDefaults] setObject:user.token forKey:@"token"];
        [[NSUserDefaults standardUserDefaults] setObject:user.phone forKey:@"phone"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    [SaveManager saveUserModel:user];
}

@end
